<template>
  <div class='login'>
    <!-- 导航栏 -->
    <van-nav-bar
      title="黑马头条-登陆"
    />

    <!-- 表单部分 -->
    <van-cell-group>
      <van-field
        v-model="userInfo.mobile"
        required
        label="手机号"
        placeholder="请输入手机号"
        :error-message="mobileErrorMsg"
      />
      <van-field
        v-model="userInfo.code"
        required
        label="密码"
        type="password"
        placeholder="请输入密码号"
        :error-message="codeErrorMsg"
      />
    </van-cell-group>

    <!-- 登陆按钮 -->
    <div class="btn-wrap">
      <van-button type="info" class="btn" @click="hLogin">登陆</van-button>
    </div>
    当前是否已登录? {{$store.state.tokenInfo.token? '已登录' : '未登录'}}
  </div>
</template>

<script>
// import axios from '../../../utils/request'
import { login, getProfile } from '../../store/user'
export default {
  name: 'login',
  data () {
    return {
      userInfo: {
        mobile: '13912345678',
        code: '246810'
      },
      mobileErrorMsg: '',
      codeErrorMsg: ''
    }
  },
  methods: {
    // 用来做校验
    // 手机号: /\d{11}/
    // 密码: /\d{6}/
    validtor () {
      this.mobileErrorMsg = /^1[3456789]\d{9}$/.test(this.userInfo.mobile) ? '' : '手机号不对'
      this.codeErrorMsg = /^\d{6}$/.test(this.userInfo.code) ? '' : '密码不对'
      // 如果ErrMsg都是''，就说明通过了验证
      //   if (this.mobileErrorMsg === '' && this.codeErrorMsg === '') {
      //     return true
      //   }
      return (this.mobileErrorMsg === '' && this.codeErrorMsg === '')
    },
    async hLogin () {
      if (!this.validtor()) {
        this.$toast.loading({
          duration: 0, // 持续展示 toast,永远不会关闭
          overlay: true, // 整体添加一个遮罩
          message: '加载中...'
        })
      }
      const { mobile, code } = this.userInfo
      this.$toast.loading({
        duration: 0, // 持续展示 toast,永远不会关闭
        overlay: true, // 整体添加一个遮罩
        message: '加载中...'
      })
      try {
        const result1 = await login(mobile, code)
        this.$store.commit('mSetToken', result1.data.data)
        const result2 = await getProfile()
        console.log(result1, result2)
        this.$toast.success('登陆成功')
        this.$router.push('/')
      } catch (err) {
        this.$toast.fail('登陆失败')
        console.log(err)
      }
    }
  }
}
</script>

<style lang="less" scoped>
    .login {
        .btn-wrap {
            padding: 0 15px;
            .btn {
                width: 100%;
                background-color: #6db4fd;
                color:#fff;
            }
        }
    }
</style>
